const express = require('express');
const moment = require('moment');
// 引入body-parser，解析post表单
const bodyParser = require('body-parser');

const app = express();

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}));

// parse application/json
app.use(bodyParser.json());

app.use("/public/", express.static("./public/"));

var comments = [
    {
        name: "小明",
        message: "你好",
        dateTime: "2019-07-03",
    }, {
        name: "小明2",
        message: "你好2",
        dateTime: "2019-07-03",
    }, {
        name: "小明3",
        message: "你好3",
        dateTime: "2019-07-03",
    },
];

// 模板引擎

app.engine('html', require('express-art-template'));

// 更改默认路径
// app.set('views', "./public");

// res.render会默认查找views目录

app.get("/", (req, res) => {
    res.render('index.html', {comments: comments});
});

app.get("/post", (req, res) => {
    res.render("post.html")
});

// 以post请求执行函数
app.post("/pinglun", (req, res) => {
    var comment = req.body;
    console.log(comment);
    comment.dateTime = moment().format("YYYY-MM-DD hh:mm:ss");
    comments.unshift(comment);
    res.redirect("/");
});

// app.get("/pinglun", (req, res) => {
//     // 存储单个评论
//     comment = req.query;
//     comment.dateTime = moment().format("YYYY-MM-DD hh:mm:ss");
//     comments.unshift(comment);
//     //302重定向
//     // res.statusCode = 302;
//     // res.setHeader('Location', '/')
//
//     res.redirect("/")
// });

app.listen(2500, () => {
    console.log("this server is running at http://127.0.0.1:2500")
});


